package com.github.anastr.speedview.slice;

import com.github.anastr.speedview.ControlAbility;
import com.github.anastr.speedview.ResourceTable;
import com.github.anastr.speedviewlib.SpeedView;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;

import java.util.Locale;

public class SpeedViewAbilitySlice extends AbilitySlice {

    SpeedView speedView;
    Slider slider;
    Button ok;
    Text textSpeed;


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_speed_view);

        speedView = (SpeedView) findComponentById(ResourceTable.Id_speedView);
        slider = (Slider) findComponentById(ResourceTable.Id_slider);
        textSpeed = (Text) findComponentById(ResourceTable.Id_textSpeed);
        ok = (Button) findComponentById(ResourceTable.Id_ok);

        ok.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                speedView.speedTo(slider.getProgress());
            }
        });

        slider.setValueChangedListener(new Slider.ValueChangedListener() {
            @Override
            public void onProgressUpdated(Slider slider, int progress, boolean fromUser) {
                textSpeed.setText(String.format(Locale.getDefault(), "%d", progress));
            }

            @Override
            public void onTouchStart(Slider slider) {

            }

            @Override
            public void onTouchEnd(Slider slider) {

            }
        });

        findComponentById(ResourceTable.Id_control).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent = new Intent();
                Operation operation = new Intent.OperationBuilder()
                        .withBundleName(getBundleName())
                        .withAbilityName(ControlAbility.class)
                        .build();
                intent.setOperation(operation);
                startAbility(intent);
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    protected void onStop() {
        super.onStop();
        speedView.onComponentUnboundFromWindow(speedView);
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
